import { useUserStore } from "@/store";
import { getCurrentUserInfo } from "@/api/module/user.api.ts";
import { lazy } from "@/util/lazy.ts";

import type { GuardInstaller } from "@/router";

/*
    负责拉取当前用户信息的路由守卫
 */

const userStore = lazy(() => useUserStore());

const installer: GuardInstaller = {
    priority: 9999,
    install: function (router) {
        // @ts-ignore
        router.beforeResolve((to, from, next) => {
            // 当页面需要认证并且当前本地没有用户信息时拉取用户信息
            if (to.meta.authentication && !userStore().containsUser) {
                return getCurrentUserInfo().then(info => {
                    userStore().updateUser(info);
                    next();
                }).catch(() => {
                    next({ name: "login" });
                });
            }
            next();
        });
    }
}

export default installer;